package com.yfkj.common.message.script.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;

import com.tencentcloudapi.sms.v20210111.models.SendStatus;
import com.yfkj.common.message.domain.SmsRecord;
import com.yfkj.common.message.domain.sms.SmsParam;
import com.yfkj.common.message.dto.account.sms.AliSmsAccount;
import com.yfkj.common.message.dto.account.sms.TencentSmsAccount;
import com.yfkj.common.message.enums.EnumUtil;
import com.yfkj.common.message.enums.SmsAccountEnum;
import com.yfkj.common.message.enums.SmsStatus;
import com.yfkj.common.message.script.SmsScript;
import com.yfkj.common.message.utils.AccountUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


import java.util.*;
import java.util.stream.Collectors;

/**
 * 阿里云短信发送
 */
@Component("AliSmsScript")
public class AliSmsScript implements SmsScript {

    @Value("${yfkj.message.accountConfig.smsAccount}")
    private String accountConfig;

    @Autowired
    private AccountUtils accountUtils;

    @Override
    public List<SmsRecord> send(SmsParam smsParam) {
        try {

            AliSmsAccount aliSmsAccount = accountUtils.getAccount(accountConfig, AliSmsAccount.class);
            Client client = init(aliSmsAccount);
            SendSmsRequest request = assembleSendReq(smsParam);
            SendSmsResponse sendSmsResponse = client.sendSms(request);
            return  assembleSendSmsRecord(smsParam,sendSmsResponse,aliSmsAccount);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<SmsRecord> pull(Integer id) {
        return null;
    }

    /**
     * 组装发送短信参数
     */
    private SendSmsRequest assembleSendReq(SmsParam smsParam) {
        SendSmsRequest request = new SendSmsRequest();

        request.setTemplateCode(smsParam.getTemplateId());
        request.setPhoneNumbers(smsParam.getPhones().stream().collect(Collectors.joining(",")));
        request.setSignName(smsParam.getSignName());
        request.setTemplateParam(JSONObject.toJSONString(smsParam.getParam()));

        return request;
    }

    /**
     * 初始化 client
     *
     * @param account
     * @return
     */
    private Client init(AliSmsAccount account)  {
        Config config = new Config()
                .setAccessKeyId(account.getAccessKeyId())
                .setAccessKeySecret(account.getAccessKeySecret());
        config.endpoint = account.getUrl();
        Client client = null;
        try {
            client = new Client(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }

    /**
     * 组装 发送消息的 返回值
     *
     * @param smsParam
     * @param response
     * @param  account
     * @return
     */
    private List<SmsRecord> assembleSendSmsRecord(SmsParam smsParam, SendSmsResponse response, AliSmsAccount account) {
        if (Objects.isNull(response) || ArrayUtil.isEmpty(response.getBody())) {
            return null;
        }

        List<SmsRecord> smsRecordList = new ArrayList<>();
//        for (SendStatus sendStatus : response.getSendStatusSet()) {
//
//            // 腾讯返回的电话号有前缀，这里取巧直接翻转获取手机号
//            String phone = new StringBuilder(new StringBuilder(sendStatus.getPhoneNumber())
//                    .reverse().substring(0, PHONE_NUM)).reverse().toString();
//
//            SmsRecord smsRecord = SmsRecord.builder()
//                    .sendDate(Integer.valueOf(DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN)))
//                    .messageTemplateId(smsParam.getMessageTemplateId())
//                    .phone(Long.valueOf(phone))
//                    .supplierId(tencentSmsAccount.getSupplierId())
//                    .supplierName(tencentSmsAccount.getSupplierName())
//                    .msgContent(smsParam.getContent())
//                    .seriesId(sendStatus.getSerialNo())
//                    .chargingNum(Math.toIntExact(sendStatus.getFee()))
//                    .status(SmsStatus.SEND_SUCCESS.getCode())
//                    .reportContent(sendStatus.getCode())
//                    .created(Math.toIntExact(DateUtil.currentSeconds()))
//                    .updated(Math.toIntExact(DateUtil.currentSeconds()))
//                    .build();
//
//            smsRecordList.add(smsRecord);
//        }
        return smsRecordList;
    }
}
